﻿//------------------------------------------------------------------------------
// ╭─────────────────────────────╮
// │ ╭─╮     ╭─╮              TM │   ╠═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╣
// │ │ │     │ │                 │                                           ☺  
// │ │ ╰───╮ │ │ ╭─────╮ ╭─────╮ │     Name:Wedn.Net 客户端请求操作助手类  ♮ ♪ ♩
// │ │ ╭─╮ │ │ │ │ ╭─╮ │ │ ╭─╮ │ │                                    ♫ ♭      
// │ │ ╰─╯ │ │ │ │ ╰─╯ │ │ ╰─╯ │ │     Author:iceStone               ♬ ♪       
// │ └─────╯ └─╯ ╰─────╯ ╰───╮ │ │     Chinese:汪磊                              
// │                     ┌───╯ │ │                                              
// │                     ╰─────╯ │   ╠═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╣
// ╰─────────────────────────────╯                                              
//------------------------------------------------------------------------------
using System;
using System.Linq;
using System.Web;

namespace Wedn.Net.Utility
{
    /// <summary>
    /// 客户端请求操作助手类
    /// </summary>
    public class RequestHelper
    {
        /// <summary>
        /// 当前页面是否为Post请求
        /// </summary>
        public static bool IsPost
        {
            get
            {
                return HttpContext.Current.Request.HttpMethod.Equals("POST");
            }
        }

        /// <summary>
        /// 当前页面是否为Get请求
        /// </summary>
        public static bool IsGet
        {
            get
            {
                return HttpContext.Current.Request.HttpMethod.Equals("GET");
            }
        }

        /// <summary>
        /// 当前页面是否是跨站提交
        /// </summary>
        public static bool IsCrossSitePost
        {
            get
            {
                if (IsPost)
                {
                    if (UrlReferrer.Length < 7)
                        return true;
                    var u = new Uri(UrlReferrer);
                    return u.Host != Host;
                }
                return false;
            }
        }

        /// <summary>
        /// 获得主机头
        /// </summary>
        public static string Host
        {
            get
            {
                return HttpContext.Current.Request.Url.Host;
            }
        }

        /// <summary>
        /// 判断是否存在指定名称的QueryString参数
        /// </summary>
        /// <param name="strName">参数名</param>
        /// <returns>是否存在</returns>
        public static bool ExistsQuery(string strName)
        {
            HttpRequest request = HttpContext.Current.Request;
            if (request.QueryString.Count == 0)
                return false;
            string req = request.QueryString.ToString();
            if (!req.Contains(strName))
                return false;
            return true;
        }

        /// <summary>
        /// 获得指定QueryString参数的值
        /// </summary>
        /// <param name="strName">QueryString参数名</param>
        /// <returns>QueryString参数的值</returns>
        public static string QueryString(string strName)
        {
            return QueryString(strName, false);
        }

        /// <summary>
        /// 获得指定QueryString参数的值
        /// </summary>
        /// <param name="strName">QueryString参数名</param>
        /// <param name="isLower">是否转化成小写</param>
        /// <returns>QueryString参数的值</returns>
        public static string QueryString(string strName, bool isLower)
        {
            string temp = HttpContext.Current.Request.QueryString[strName];
            if (temp == null)
                return string.Empty;
            if (isLower)
                return StringHelper.UrlDecode(temp.ToLower());
            return StringHelper.UrlDecode(temp);
        }

        /// <summary>
        /// 获得指定QueryString参数的int类型值
        /// </summary>
        /// <param name="strName">QueryString参数名</param>
        /// <returns>QueryString参数的int类型值</returns>
        public static int QueryInt(string strName)
        {
            return StringHelper.StrToInt(HttpContext.Current.Request.QueryString[strName], 0);
        }

        /// <summary>
        /// 获得指定QueryString参数的int类型值
        /// </summary>
        /// <param name="strName">QueryString参数名</param>
        /// <param name="defValue">缺省值</param>
        /// <returns>QueryString参数的int类型值</returns>
        public static int QueryInt(string strName, int defValue)
        {
            return StringHelper.StrToInt(HttpContext.Current.Request.QueryString[strName], defValue);
        }

        /// <summary>
        /// 获得指定Form参数的值
        /// </summary>
        /// <param name="strName">Form参数名</param>
        /// <returns>Form参数的值</returns>
        public static string FormString(string strName)
        {
            string str = HttpContext.Current.Request.Form[strName];
            if (str == null)
                return string.Empty;
            return str;
        }

        ///// <summary>
        ///// 请求页面类型
        ///// </summary>
        //public static PageType QueryType
        //{
        //    get
        //    {
        //        string rurl = HttpContext.Current.Request.RawUrl.Replace(Config.SiteUrl.TrimEnd('/'), string.Empty).ToLower();
        //        if (string.IsNullOrEmpty(rurl))
        //            return PageType.Default;
        //        if (rurl.Contains("post=") || rurl.Contains("/post/"))
        //            return PageType.Post;
        //        if (rurl.Contains("cate=") || rurl.Contains("/category/"))
        //            return PageType.Category;
        //        if (rurl.Contains("tag=") || rurl.Contains("/tag/"))
        //            return PageType.Tag;
        //        if (rurl.Contains("arch=") || rurl.Contains("/archive/"))
        //            return PageType.Archive;
        //        if (rurl.Contains("page=") || rurl.Contains("/page/"))
        //            return PageType.Page;
        //        return PageType.Default;
        //    }
        //}

        /// <summary>
        /// 获得指定Form参数的int类型值，缺省值为0
        /// </summary>
        /// <param name="strName">Form参数名</param>
        /// <returns>Form参数的int类型值</returns>
        public static int FormInt(string strName)
        {
            return StringHelper.StrToInt(HttpContext.Current.Request.Form[strName], 0);
        }

        /// <summary>
        /// 获得指定Form参数的int类型值
        /// </summary>
        /// <param name="strName">Form参数名</param>
        /// <param name="defValue">缺省值</param>
        /// <returns>Form参数的int类型值</returns>
        public static int FormInt(string strName, int defValue)
        {
            return StringHelper.StrToInt(HttpContext.Current.Request.Form[strName], defValue);
        }

        /// <summary>
        /// 客户端IP地址
        /// </summary>
        public static string IPAddress
        {
            get
            {
                string result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
                if (string.IsNullOrEmpty(result))
                    result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
                if (string.IsNullOrEmpty(result))
                    result = HttpContext.Current.Request.UserHostAddress;
                if (string.IsNullOrEmpty(result) || !StringHelper.IsIP(result))
                    return "0.0.0.0";
                return result;
            }
        }

        /// <summary> 
        /// 获得当前URL(重写前)
        /// 中文编码问题，默认页问题
        /// </summary>
        public static string CurrentUrl
        {
            get
            {
                return "http://" + HttpContext.Current.Request.Url.Authority + HttpContext.Current.Request.RawUrl;
            }
        }

        /// <summary>
        /// 获取有关客户端上次请求的 URL 的信息，该请求链接到当前的 URL。
        /// </summary>
        public static string UrlReferrer
        {
            get
            {
                return Convert.ToString(HttpContext.Current.Request.UrlReferrer);
            }
        }

        //private static readonly Regex MobileRegex = new Regex(@"(nokia|sonyericsson|blackberry|iphone|samsung|sec\-|windows ce|motorola|mot\-|up.b|midp\-)", RegexOptions.IgnoreCase | RegexOptions.Compiled);
        /// <summary>
        /// 是否是手机浏览
        /// opera没搞定
        /// </summary>
        public static bool IsMobile
        {
            get
            {
                HttpContext context = HttpContext.Current;
                if (context != null)
                {
                    HttpRequest request = context.Request;
                    string accept = request.ServerVariables["HTTP_ACCEPT"];
                    if (!string.IsNullOrEmpty(accept) && accept.IndexOf("wap", StringComparison.Ordinal) > 0)
                        return true;
                }

                return false;
            }
        }

        /// <summary>
        /// 返回客户端浏览器版本
        /// 如果是IE类型，返回版本数字
        /// 如果不是IE类型，返回-1
        /// </summary>
        /// <returns>一位数字版本号</returns>
        public static int GetClientBrowserVersion()
        {
            string userAgent = HttpContext.Current.Request.ServerVariables["HTTP_USER_AGENT"];

            if (userAgent.IndexOf("MSIE", StringComparison.Ordinal) < 0) return -1;

            string version = userAgent.Substring(userAgent.IndexOf("MSIE", StringComparison.Ordinal) + 5, 1);
            int res;
            if (int.TryParse(version, out res))
                return res;
            return -1;
        }

        /// <summary>
        /// 判断是否来自搜索引擎链接
        /// </summary>
        /// <returns>是否来自搜索引擎链接</returns>
        public static bool IsSearchEngine
        {
            get
            {
                if (HttpContext.Current.Request.UrlReferrer == null)
                    return false;

                string[] searchEngines = { "google", "yahoo", "msn", "baidu", "sogou", "sohu", "sina", "163", "lycos", "tom", "yisou", "iask", "soso", "gougou", "zhongsou" };
                var tmpReferrer = HttpContext.Current.Request.UrlReferrer.ToString().ToLower();
                return searchEngines.Any(t => tmpReferrer.IndexOf(t, StringComparison.Ordinal) >= 0);
            }
        }
    }
}